#!/bin/bash -e

function info() {
    echo Usage: `basename $0` '[-wrb] bam control'
    exit 1
}

while getopts ":p:f:w:r:b:" opt; do
    case  $opt  in
        p) out_prefix=$OPTARG;;
        f) suffix=$OPTARG;;
        w) win_len=$OPTARG;;
        r) read_th=$OPTARG;;
        b) bed=$OPTARG;;
        *) info;;
    esac
done
shift $(($OPTIND - 1))

if [ $# -lt 1 ]; then info; fi

# perl get_fasta_lengths.pl MyGenome.fa
fc_home=~/freec
PATH=$fc_home/src:$PATH
scripts=$fc_home/scripts
data_home=$fc_home/data
chr=$data_home/chr
len=$data_home/len
win_len=${win_len:=50000}
gc0=GC_profile.${win_len}bp.cnp
gc=$data_home/$gc0
min_length=3
noisyData=FALSE

bam=$1
ctrl=$2
mo=0
out_prefix=${out_prefix:=1}
win_step=${win_step:=10000}
th_r=${read_th:=50}
config=$out_prefix.config_fc


cat << general > $config
[general]

maxThreads=6
readCountThreshold=$th_r
chrLenFile = $len
ploidy = 2
window = $win_len
minCNAlength=$min_length

breakPointThreshold = 0.8
#coefficientOfVariation = 0.062
chrFiles = $chr
#outputDir = .
#degree=3

general

if test -z "$2" && test -f "$gc"; then
cat << gc >> $config
GCcontentProfile = $gc
gc
fi


cat << sample >> $config
[sample]

mateFile = $bam
inputFormat = BAM
mateOrientation = $mo

sample

if test -n "$2"; then
cat << control >> $config
[control]

mateFile = $ctrl
inputFormat = BAM
mateOrientation = $mo
control
fi

if test -n "$bed"; then
cat << target >> $config
[target]

captureRegions = $bed

target
fi

freec -conf $config

p1=`basename $1`
# p2=`basename $2`
rename $p1 $out_prefix ${p1}_*

# cat $scripts/assess* |R --slave --args ${out_prefix}_CNVs ${out_prefix}_ratio.txt
# source("http://bioconductor.org/biocLite.R")
# biocLite("rtracklayer")

cat $scripts/makeGraph.R | R --slave --args 2 ${out_prefix}_ratio.txt

if test -s "$gc0"; then
    mv $gc0 $gc
fi


